

import React, { FC, useEffect, useRef, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { Http } from '../../api'
import MyHead from '../../components/MyHead'
import { Stepper, Button, Form, Toast, List, CapsuleTabs, Modal, Popup } from 'antd-mobile'
import { HeartOutline, SmileOutline, EditSOutline } from 'antd-mobile-icons'
import { ListItem } from 'antd-mobile/es/components/list/list-item'
import "./index.scss"
import { connect } from 'react-redux'

const Good: FC<{
  // 接收用户信息
  userInfo: any  //这里存的是个对象
}> = (
  // 注意：对象要解构
  { userInfo }
) => {
    const formRef: any = useRef()
    const [form] = Form.useForm()
    const params = useParams()
    const [searchParams] = useSearchParams() // 获取query值
    const [data, setData] = useState<any>(null)
    const router = useNavigate()  //跳转
    let [count, setCount] = useState<number>(1)   //购买数量


    let [likeNum, setLikeNum] = useState<number>(0)  //商品点赞的数量
    let [hasLike, sethasLike] = useState<boolean>(false)  //是否点赞

    let[commentNum,setCommentNum] = useState<number>(0) //商品的评论数量
    let [hasComment,sethasComment] = useState<boolean>(false)  //是否评论

    let [visible1, setVisible1] = useState<boolean>(false)


    // 收藏

    let [collectNum, setCollectNum] = useState<number>(0)
    let [hasCollect, setHasCollect] = useState<boolean>(false)

    const getGoodData = async () => {
      let res: any = await Http.getgoodone({
        _id: params.goodId,
      })
      setData(res.result)
    }

    const checkIsLogin = (next?: any) => {
      // 判断是否登录了
      if (userInfo) {
        console.log(userInfo);
        next()
        // console.log(1);

      } else {
        Modal.confirm({
          content: "请先登录",
          title: "提示",
          onConfirm: () => {
            router("/login")  //如果我是从 Good 页面跳的登录，登录成功后，返回对应的页面
          }
        })
      }
    }

  

    const addToCart=()=>{
      // 是否登录
      checkIsLogin(async()=>{
        // 你是否购买过
        let res:any = await Http.getcart({
          // 查询条件
          goodId:params.goodId,
          phone:userInfo.phone,
        })
        if (res.result.length>0) {
          // 购买过
          // count 数量++
          let value:any= await Http.getcart({
            _id:res.result[0]._id,
            count:res.result[0].count+count
          })
          if (value.code==200) {
            Toast.show({
              content:"再次加入购物车成功"
            })
          }
        }else{
          // 没有购买过
          let value:any = await Http.addcart({
             // 查询条件
          goodId:params.goodId,
          phone:userInfo.phone,
          good:data,  //商品全部信息
          count:count //加入购物车的数量
          })
          if (value.code == 200) {
            Toast.show({
              content:"加入购物车成功"
            })
          }
        }
        
      })
    }
    // 没有登陆 
    // 没有 去登陆
    // 登陆 
    
    // 去登陆，评论
    


    const todoCommentAction=()=>{
      checkIsLogin(async()=>{
        // setVisible1(false)
        // 开始评论逻辑
        // hasComment true 已经评论
        // hasComment false 没有评论
        if (hasComment) {
          let res:any = await Http.getcomment({
            goodId: params.goodId,
            phone: userInfo.phone,
            good: data,
          })

        if (res.code ==200) {
          Toast.show({
            content:"你以评论，如需修改请到个人中心"
          })
          sethasComment(true)
          // setVisible1(false)
          // console.log('已经评论');
          // console.log(111);
          }
        }
        else{
          // 没有评论 直接评论
          let res:any = await Http.addcomment({
            goodId: params.goodId,
            phone: userInfo.phone,
            good: data,
          })
          if ((res.code==200)) {
            console.log(22);
            setVisible1(true)
          }
          
        //  sethasComment(true);
        //  setCommentNum(commentNum + 1);
        }
      })
    }



    const todoLikeAction = () => {
      checkIsLogin(async () => {
        // 回调
        // 开始点赞逻辑
        // hasLike true 已经点赞
        // hasLike false 没有点赞 
        if (hasLike) {
          // 取消点赞
          let res: any = await Http.dellikes({
            goodId: params.goodId,
            phone: userInfo.phone,
          })
          if (res.code == 200) {
            Toast.show({
              content: "取消点赞了"
            })
            sethasLike(false)
            setLikeNum(likeNum - 1);
          }
        } else {
          // 直接点赞
          let res: any = await Http.addlikes({
            // 商品id 手机号 商品信息
            goodId: params.goodId,
            phone: userInfo.phone,
            good: data
          })
          if (res.code == 200) {
            Toast.show({
              content: "点赞成功"
            })
            sethasLike(true);
            setLikeNum(likeNum + 1)
          }
        }
      })
    }

    const todoCollectAction = () => {
      checkIsLogin(async () => {
        // 收藏逻辑
        // hasCollect true 已经点赞
        // hasCollect false 没有点赞 
        if (hasCollect) {
          // 取消搜藏
          let res: any = await Http.delcollect({
            goodId: params.goodId,
            phone: userInfo.phone,
          })
          if (res.code == 200) {
            Toast.show({
              content: "取消收藏"
            })
            setHasCollect(false)
            setCollectNum(collectNum - 1)
          }
        } else {
          // 直接收藏
          let res: any = await Http.addcollect({
            // 商品id 手机号 商品信息
            goodId: params.goodId,
            phone: userInfo.phone,
            good: data
          })
          if (res.code == 200) {
            Toast.show({
              content: '收藏成功'
            })
            setHasCollect(true)
            setCollectNum(collectNum + 1)
          }
        }
      })
    }

    // 这个商品的评论次数
    const getComments = async()=>{
      let res :any = await Http.getcomment({
        goodId:params.goodId
      })
      setCommentNum(res.result.length)
    }


    // 这个商品点赞的次数
    const getLikeCounts = async () => {
      let res: any = await Http.getlikes({
        // 通过商品的 ID 去查
        goodId: params.goodId,
      })
      setLikeNum(res.result.length)
    }

    // 是否已经点赞
    const getHasLike = async () => {
      let res: any = await Http.getlikes({
        // 通过 商品ID 和 手机号查
        goodId: params.goodId,
        phone: userInfo.phone
      })
      sethasLike(!!res.result.length)
    }

    // 这个商品被收藏次数
    const getCollectCounts = async () => {
      let res: any = await Http.getcollect({
        goodId: params.goodId,
      })
      setCollectNum(res.result.length)
    }

    // 本人是否已经收藏
    const getHasCollect = async () => {
      let res: any = await Http.getcollect({
        // 通过 商品ID 和 手机号查
        goodId: params.goodId,
        phone: userInfo.phone
      })
      setHasCollect(!!res.result.length)
    }

    useEffect(() => {
      getGoodData()
      getLikeCounts()

      getCollectCounts()

      getComments()  //评论数量


      // 已经登陆
      if (userInfo) {
        getHasLike()
        getHasCollect()
      }


    }, [])
    
    return (
      <div className='good'>
        <MyHead title={searchParams.get('name')} />
        {
          data && (
            <div>
              <img src={data.img} alt="" style={{ margin: '0 auto', width: '100%', height: '433px' }} />
              <div className='gbox'>
                <List mode="card">
                  <List.Item extra={data.name}>商品名称</List.Item>
                  <List.Item extra={data.price}>商品价格</List.Item>
                  <List.Item extra={data.type.text}>商品类型</List.Item>
                  <List.Item extra={data.discount}>商品折扣</List.Item>
                  <List.Item extra={<Stepper min={1} max={5}
                    defaultValue={count}
                    onChange={(value: any) => {
                      setCount(value)
                    }}
                  />}>购买数量</List.Item>
                  <List.Item extra={Math.round(data.price * data.discount / 10 * count).toFixed(2)}>商品小计</List.Item>
                </List>
              </div>

              <div className="gfoot">
                {/* <div className=" gfoot ">收藏</div> */}
                {
                  hasLike ? <div style={{ fontSize: '40px', lineHeight: '70px', margin: '0 10px' }} onClick={todoLikeAction}><HeartOutline style={{ color: '#f50' }} />({likeNum})</div>
                    : <div style={{ fontSize: '40px', lineHeight: '70px', margin: '0 10px', }} onClick={todoLikeAction}><HeartOutline />({likeNum})</div>
                }
                {/* <div className="gbtn">收藏</div> */}
                {
                  hasCollect ? <div style={{ fontSize: '40px', lineHeight: '70px', margin: '0 10px' }} onClick={todoCollectAction}><SmileOutline style={{ color: '#f50' }} />({collectNum})</div>
                    : <div style={{ fontSize: '40px', lineHeight: '70px', margin: '0 10px' }} onClick={todoCollectAction}><SmileOutline />({collectNum})</div>
                }
                {/* {
                  <div className={hasComment ? "gbtn color1":"gbtn color2 "} onClick={todoCommentAction} >{hasComment?'已评论':'未评论'}({commentNum})</div>
                  onClick={() => {
                      
                      setVisible1(true)
                    }}
                } */}


                {
                  hasComment ? <div className="gbtn color1" onClick={todoCommentAction}>

                    已评论({commentNum})
                    <Popup
                      visible={visible1}
                      onMaskClick={() => {
                        setVisible1(true)
                      }}
                      bodyStyle={{ height: '40vh' }}>
                      <div
                        style={{ height: '40vh', overflowY: 'scroll', padding: '20px', fontSize: '30px' }}
                      >
                        111
                      </div>
                    </Popup>
                  </div>
                    : <div className="gbtn color1" onClick={todoCommentAction}>未评论({commentNum}) <Popup
                      visible={visible1}
                      onMaskClick={() => {
                        setVisible1(true)
                      }}
                      bodyStyle={{ height: '40vh' }}
                    >
                      <div
                        style={{ height: '40vh', overflowY: 'scroll', padding: '20px', fontSize: '30px' }}
                      >

                       222
                  </div>
                </Popup></div>
                  
                }
              
          
              
                <div className="gbtn color1" onClick={addToCart}>加入购物车</div>
                <div className="gbtn color1"onClick={()=>router('/payorder?amount='+ Math.round(data.price * data.discount / 10 * count ).toFixed(2))} >立即购买</div>
              </div>

            </div>
          )
        }

      </div>
    )
  }

export default connect(
  // 获取登录信息
  (state: any) => {
    return {
      userInfo: state.getIn(['data', 'userInfo']),

    }
  }
)(Good)







